﻿namespace TC
{
    [Menu("FlowControl/Foreach")]
    public class Foreach<T> : FlowControlNode, IRepeat
    {
        public int i = 0;
        public int count = 10;

        public FlowInput<FlowNode> flowIn;
        public FlowOutput<FlowNode> flowI;
        public FlowOutput<FlowNode> flowFinish;

        public ValueInput<T[]> list;
        public ValueOutput<T> cur;

        public override void OnCreate()
        {
            base.OnCreate();

            flowIn = this.AddFlowInPort<FlowNode>("In");
            flowI = this.AddFlowOutPort<FlowNode>("I");
            flowFinish = this.AddFlowOutPort<FlowNode>("Finish");

            list = this.AddValueInPort<T[]>("array");
            cur = this.AddValueOutPort<T>("item", () =>
            {
                return list.Value[i];
            });
        }

        public override void Execute(Dispatcher chain)
        {
            base.Execute(chain);

            count = list.Value.Length;
            if (i < count)
            {
                ++i;
                chain.Call(flowI);
                
            }
            else if (i == count)
            {
                chain.Call(flowFinish);
            }
            else
            {
                chain.End(0);
            }
        }

        public override void Stop()
        {
            base.Stop();

            i = 0;
        }

        public void Next(int status)
        {
            Execute(chain);
        }
    }
}
